import React from "react";
import { Terminal } from "xterm";
import { FitAddon } from "xterm-addon-fit";
import 'xterm/css/xterm.css'
import {
  TerminalConnector
} from "./TerminalConnector";

export function Xterm(props: any) {
  let { command } = props;

  const [curTerminal, setTerminal] = React.useState(null);
  const [curConnector, setConnector] = React.useState(null);

  React.useEffect(() => {
    if (curTerminal) {
      // @ts-ignore
      curTerminal.dispose();
    }
    if (curConnector) {
      // @ts-ignore
      curConnector.detachTerminal();
    }
    let terminal = new Terminal({ cursorBlink: true });
    let fitAddon = new FitAddon();
    let connector = new TerminalConnector({
      handleOpen,
      handleMessage,
      handleClose,
      handleError,
    });
    // @ts-ignore
    setTerminal(terminal);
    // @ts-ignore
    setConnector(connector);
    function handleOpen() {
      // fitAddon.fit();
      // terminal.focus();

      // window.onresize = function () {
      //   fitAddon.fit();
      // };
    }

    function handleMessage(data: any) {
      // 接收服务器数据，将数据写入shell
      terminal.write(data);

    }

    function handleClose() {
      terminal.writeln("Exit");
    }

    function handleError(e: any) {
      terminal.writeln("");
      terminal.writeln("Sorry, connection has some error.");
    }

    terminal.loadAddon(fitAddon);
    // @ts-ignore
    terminal.open(document.getElementById("terminal"));
    terminal.onResize(({ cols, rows }) => {
      // console.log("resize: " + size)
      const msg = { operation: "resize", cols: cols, rows: rows }
      connector.handleSend(
        JSON.stringify(msg)
      );
    });
    terminal.onData((data) => {
      const msg = { operation: "stdin", data: data }
      //conn.send(JSON.stringify(msg))
      connector.handleSend(JSON.stringify(msg));
    });
  }, [command]);

  return <div id="terminal"></div>;
}